package com.bifang.module.file.dao.service.impl;

import cn.hutool.core.convert.Convert;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.module.file.common.cache.FileCacheConst;
import com.bifang.module.file.common.vo.fileAppRead.FileAppReadVO;
import com.bifang.module.file.dao.model.FileAppRead;
import com.bifang.module.file.dao.mapper.FileAppReadMapper;
import com.bifang.module.file.dao.service.FileAppReadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;

/**
 * 应用读取文件权限表服务实现类
 *
 * @author xyh
 * @since 2023-03-17
 */
@Service
public class FileAppReadServiceImpl extends ServiceImpl<FileAppReadMapper, FileAppRead> implements FileAppReadService {

    @Override
    public FileAppReadVO getFileReadDetail(String fileClassCode, Long appId) {
        if (StringUtils.isBlank(fileClassCode)) {
            throw new AppException("文件分类编号不能为空");
        }
        if (appId == null) {
            throw new AppException("应用id不能为空");
        }
        FileAppReadVO fileAppReadVO;
        String key = appId + ":" + fileClassCode;
        // 判断是否存在缓存中 在缓存中的，获取缓存数据
        Cache<String,FileAppReadVO> cache = JetCacheUtils.create(FileCacheConst.FILEREADINFOAPPID, CacheType.BOTH, Duration.ofSeconds(86400),Duration.ofSeconds(300));
        if (cache.get(key)!=null) {
            fileAppReadVO = cache.get(key);
        } else {

            QueryWrapper<FileAppRead> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(FileAppRead::getAppId,appId)
                    .eq(FileAppRead::getFileClassCode,fileClassCode)
                    .eq(FileAppRead::getAuthStatus, AuthStatusEnum.YES.getType());
            List<FileAppRead> list = this.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)){
                fileAppReadVO= Convert.convert(FileAppReadVO.class,list.get(0));
                cache.put(key, fileAppReadVO);
            }else{
                fileAppReadVO=null;
            }


        }
        return fileAppReadVO;
    }
}
